<template>
    <div>
        <!-- 面包屑路径导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>分类品牌管理</el-breadcrumb-item>
            <el-breadcrumb-item>品牌管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card class="box-card">
            <!-- 搜索和添加组件区域 -->
            <el-row :gutter="20" >
                <el-col :span="7" >
                    <el-input
                    placeholder="请输入内容"
                    v-model="searchName"
                    class="input-with-select"
                    clearable
                    @clear="getBrandList"
                    @input="getBrandList">
                        <el-button slot="append" icon="el-icon-search" @click="searchBrand" ></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addBrandDialogVisible = true" >添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户列表区域 -->
            <el-table
                :data="brandList"
                style="width: 100%"
                stripe
                border>
                <el-table-column
                type="index"
                label="#"
                width="50">
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="品牌名称">
                </el-table-column>
                <el-table-column
                label="图片">
                  <template slot-scope="scope">
                    <img style="width:100px" class="photo" :src="scope.row.image" alt="">
                  </template>
                </el-table-column>
                <el-table-column
                    prop="letter"
                    label="首字母">
                </el-table-column>
                <el-table-column
                    label="操作">
                    <template slot-scope="scope" >
                        <el-button size="mini" type="primary" icon="el-icon-edit" circle @click="showEditDialog(scope.row.id, scope.row.name, scope.row.image)" ></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="rows"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
        </el-card>

        <!-- 添加对话框 -->
        <el-dialog
          title="添加"
          :visible.sync="addBrandDialogVisible"
          width="50%"
          @close="clearaddBrandForm">
          <!-- 对话框主体内容 -->
          <el-form ref="addBrandForm"  :model="addBrandForm" label-width="80px">
            <el-form-item label="名称" prop="name" >
              <el-input v-model="addBrandForm.name"></el-input>
            </el-form-item>
            <el-form-item label="图片" prop="uTrueName" >
              <!-- 上传组件 -->
                <el-upload
                    :action="action"
                    list-type="picture-card"
                    ref="upload"
                    :before-upload="upload"
                    :data="dataOss"
                    :on-success="uploadSuccess"
                    :on-error="uploadError"
                    :on-remove="removeSkuImg">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="imgDialogVisible">
                    <img width="100%"  :src="addBrandForm.image" alt="">
                </el-dialog>
            </el-form-item>
            <el-form-item label="分类">
              <div class="block">
                <el-cascader
                  :options="categories"
                  :props="defaultProps"
                  clearable
                  filterable
                  v-model="addBrandForm.categoryIds"
                  >
                </el-cascader>
              </div>
            </el-form-item>
          </el-form>
          <!-- 对话框的操作按钮 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="addBrandDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addBrand">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 修改对话框 -->
        <el-dialog
          title="修改"
          :visible.sync="editBrandDialogVisible"
          width="50%"
          @close="cleareditBrandForm">
          <!-- 对话框主体内容 -->
          <el-tabs v-model="activeName">
            <el-tab-pane label="基本修改" name="first">
              <el-form ref="editBrandForm" :model="editBrandForm" label-width="80px">
                <el-form-item label="品牌名称" prop="uName" >
                  <el-input v-model="editBrandForm.name" ></el-input>
                </el-form-item>
                <el-form-item label="图片" prop="uTrueName" >
                  <el-upload
                    :action="action"
                    list-type="picture-card"
                    ref="upload"
                    :before-upload="upload"
                    :data="dataOss"
                    :on-success="uploadSuccess"
                    :on-error="uploadError"
                    :file-list= "fileList"
                    :on-remove="removeSkuImg">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="imgDialogVisible">
                    <img width="10%" :src="editBrandForm.image" alt="">
                  </el-dialog>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="添加分类" name="second">
              <template>
                <div  style="text-align: center;">
                  <el-transfer
                    style="text-align: left; display: inline-block"
                    v-model="checkCategorys"
                    filterable
                    :titles="['所有分类', '已选择分类']"
                    :format="{
                      noChecked: '${total}',
                      hasChecked: '${checked}/${total}'
                    }"
                    @change="handleChange"
                    :data="resource">
                    <span slot-scope="{ option }">{{ option.label }}</span>
                  </el-transfer>
                </div>
              </template>
            </el-tab-pane>
          </el-tabs>

          <!-- 对话框的操作按钮 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="editBrandDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="edit">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      checkCategorys: [1],
      renderFunc(h, option) {
        return <span>{ option.key } - { option.label }</span>
      },
      resource: [],
      defaultProps: {
        multiple: true,
        children: 'categoryVOList',
        label: 'name',
        value: 'id'
      },
      // tabs标签页显示内容
      activeName: 'first',
      options: [],
      // 搜索的关键字
      searchName: '',
      // 品牌列表集合
      brandList: [],
      // 页码
      page: 1,
      // 单页显示条数
      rows: 5,
      // 总数据条数
      total: 0,
      // 是否显示添加对话框
      addBrandDialogVisible: false,
      // 是否显示修改对话框
      editBrandDialogVisible: false,
      // 添加表单对象
      addBrandForm: {
        name: '',
        image: '',
        categoryIds: []
      },
      // 修改表单对象
      editBrandForm: {
        id: '',
        name: '',
        image: '',
        categories: []
      },
      // 所有分类
      categories: [],
      dataOss: {},
      // 保存上传接口的地址
      action: 'https://ricervcvcer-shopping.oss-cn-shenzhen.aliyuncs.com',
      // 预览图片变量
      dialogImageUrl: '',
      // 图片集合
      fileList: [],
      // 图片预览对话框是否需要显示
      imgDialogVisible: false
    }
  },
  methods: {
    async getBrandList () {
      const param = { page: this.page, rows: this.rows, brandName: this.searchName }
      const { data: result, status: state } = await this.$http.post('brand-server/brand/page', this.$qs.stringify(param))
      if (state !== 200) {
        return this.$message.error('查询失败')
      }
      this.brandList = result.data.records
      this.total = result.data.total
    },
    async getAllCategory () {
      const { data: result } = await this.$http.get('category-server/category/getAll')
      this.categories = result.data
    },
    handleSizeChange (size) {
      this.rows = size
      this.getBrandList()
    },
    handleCurrentChange (page) {
      // 将需要访问的页面赋值给vue的遍历page
      this.page = page
      // 然后重写调用查询方法，查询方法会使用最新的page进行分页查询
      this.getBrandList()
    },
    searchBrand () {
      this.getBrandList()
    },
    clearaddBrandForm () {
      // 初始化添加表单数据
      this.$refs.addBrandForm.resetFields()
    },
    cleareditBrandForm () {
      // 清楚上传数据
      this.$refs.upload.clearFiles()
    },
    addBrand () {
      // 验证用户名是否已经存在
      console.log(this.addBrandForm)
      this.$http.put('brand-server/brand/addBrand', this.addBrandForm).then(resp => {
        if (resp.data.result === 'SUCCESS') {
          this.$message.success('添加品牌成功!')
          this.addBrandDialogVisible = false
        } else {
          this.$message.error(resp.data.message)
        }
      }).catch(error => {
        this.$message.warning(error.response.data.msg)
      })
    },
    async showEditDialog (id) {
      this.$http.get('brand-server/brand/id/' + id).then(resp => {
        // 设置选中分类
        this.checkCategorys = resp.data.categories
        this.resource = this.generateData()

        // 2.填充到修改表单中
        this.editBrandForm.id = resp.data.id
        this.editBrandForm.name = resp.data.name
        this.editBrandForm.image = resp.data.image
        // 3.显示修改对话框
        this.editBrandDialogVisible = true
      }).catch(error => {
        this.$message.warning(error.response.data.msg)
      })
    },
    edit () {
      this.editBrandForm.categories = this.checkCategorys
      // 1、修改数据到数据库
      this.$http.post('brand-server/brand/update', this.editBrandForm).then(resp => {
      // 2、根据返回结果进行弹出提示
        if (resp.data.result === 'SUCCESS') {
          this.$message.success('修改成功！')
          // 3、关闭对话框
          this.editBrandDialogVisible = false
          // 4、刷新表格数据
          this.getBrandList()
        } else {
          this.$message.error(resp.data.message)
        }
      }).catch(error => {
        this.$message.warning(error.response.data.msg)
      })
    },
    async upload (file) {
      // 文件名，和后台约定
      // const fileName = 'devicesource' + file.uid + file.name
      const reponse = await this.$http.get('ricervcvcer-third-party/oss/policy')// 索要签名
      this.dataOss = {
        key: reponse.data.data.dir + '/' + file.uid + '_' + file.name,
        ossAccessKeyId: reponse.data.data.accessid,
        policy: reponse.data.data.policy,
        signature: reponse.data.data.signature,
        dir: reponse.data.data.dir,
        host: reponse.data.data.hoast
      } // 上传额外参数
      this.addBrandForm.image = this.action + '/' + reponse.data.data.dir + '/' + file.uid + '_' + file.name
      this.editBrandForm.image = this.action + '/' + reponse.data.data.dir + '/' + file.uid + '_' + file.name
    },
    uploadError () {
      this.$message.error('图片上传失败！')
    },
    uploadSuccess () {
      this.$message.success('图片上传成功！')
    },
    // 移除sku图片
    async removeSkuImg (file) {
      const formData = new FormData()
      formData.append('ossName', this.action + '/' + file.uid + '_' + file.name)
      await this.$http.post('ricervcvcer-third-party/oss/del', formData)
    },
    // 穿梭框改变
    handleChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys)
    },
    generateData () {
      const data = []
      this.categories.forEach(c1 => {
        c1.categoryVOList.forEach(c2 => {
          c2.categoryVOList.forEach(c3 => {
            data.push({
              key: c3.id,
              label: c3.name,
              disabled: this.checkCategorys.indexOf(c3.id) !== -1
            })
          })
        })
      })
      return data
    }
  },
  created () {
    this.getBrandList()
    this.getAllCategory()
  },
  computed: {

  }
}
</script>

<style lang="less" scoped>
.photo {
  width: 50px;
  height: 50px;
  border-radius: 5px
}
.transfer-footer {
  margin-left: 20px;
  padding: 6px 5px;
}
</style>
